package com.stu.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@Slf4j
public class HttpRequestUtils {
    /**
     * httpPost
     *
     * @param url       路径
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) {
        return httpPost(url, jsonParam, false);
    }

    /**
     * httpPost
     *
     * @param url       路径
     * @param jsonParam 参数
     * @return
     */
    public static int httpPostState(String url, JSONObject jsonParam) {
        return httpPostState(url, jsonParam, false);
    }

    /**
     * post请求
     *
     * @param url            url地址
     * @param jsonParam      参数
     * @param noNeedResponse 不需要返回结果
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse) {
        // post请求返回结果
        HttpClient httpClient = HttpClientBuilder.create().build();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** 请求发送成功，并得到响应 **/
            if (result.getStatusLine().getStatusCode() == 200) {
                // String str = "";
                // try {
                // /**读取服务器返回过来的json字符串数据**/
                // str = EntityUtils.toString(result.getEntity());
                // if (noNeedResponse) {
                // return null;
                // }
                // /**把json字符串转换成json对象**/
                // jsonResult = JSONObject.fromObject(str);
                // } catch (Exception e) {
                // log.error("post请求提交失败:" + url, e);
                // }
            }
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
        }
        return jsonResult;
    }

    @SuppressWarnings("finally")
    public static int httpPosts(String url, JSONObject jsonParam, boolean noNeedResponse) {
        // post请求返回结果
        int resultInfo = 0;
        try {
            HttpClient httpClient = HttpClientBuilder.create().build();

            HttpPost method = new HttpPost(url);

            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** 请求发送成功，并得到响应 **/
            resultInfo = result.getStatusLine().getStatusCode();
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
        } finally {
            return resultInfo;
        }

    }

    /**
     * post请求
     *
     * @param url       url地址
     * @param jsonParam 参数
     *                  不需要返回结果
     * @return
     */
    public static int httpPostForWrapCard(String url, JSONObject jsonParam) {
        // post请求返回结果
        HttpClient httpClient = HttpClientBuilder.create().build();
        int jsonResult = 0;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** 请求发送成功，并得到响应 **/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    str = EntityUtils.toString(result.getEntity());
                    jsonResult = result.getStatusLine().getStatusCode();
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            } else {
                jsonResult = result.getStatusLine().getStatusCode();
            }
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
        }
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) {
        // get请求返回结果
        JSONObject jsonResult = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
            // 发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** 读取服务器返回过来的json字符串数据 **/
                String strResult = EntityUtils.toString(response.getEntity());
                System.out.println(strResult);
                /** 把json字符串转换成json对象 **/
                jsonResult = JSONObject.parseObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                log.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            log.error("get请求提交失败:" + url, e);
        }
        return jsonResult;
    }

    /**
     * post请求
     *
     * @param url            url地址
     * @param jsonParam      参数
     * @param noNeedResponse 不需要返回结果
     * @return
     */
    public static int httpPostState(String url, JSONObject jsonParam, boolean noNeedResponse) {
        // post请求返回结果
        HttpClient httpClient = HttpClientBuilder.create().build();
        int jsonResult = 0;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** 请求发送成功，并得到响应 **/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    str = EntityUtils.toString(result.getEntity());
                    jsonResult = result.getStatusLine().getStatusCode();
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            } else {
                jsonResult = result.getStatusLine().getStatusCode();
            }
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
        }
        return jsonResult;
    }

    /**
     * 发送urlencode的http-post请求
     *
     * @param url       url地址
     * @param jsonParam 参数
     * @return JSONObject
     * @throws IOException
     */
    public static JSONObject httpEncodePost(String url, JSONObject jsonParam) throws IOException {
        //post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(6000).build();//设置请求和传输超时时间
        method.setConfig(requestConfig);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(URLEncoder.encode(jsonParam.toString(), "UTF-8"), "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            Header[] allHeaders = result.getAllHeaders();
            for (int i = 0; i < allHeaders.length; i++) {
                log.debug("headers+++name:{} +++value:{}", allHeaders[i].getName(), allHeaders[i].getValue());
            }
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    str = EntityUtils.toString(result.getEntity(), "UTF-8");
                    str = URLDecoder.decode(str, "UTF-8");
                    EntityUtils.consume(result.getEntity());
                    if (str != null && !"".equals(str)) {
                        jsonResult = JSONObject.parseObject(str);
                    }
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            } else {
            }
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return jsonResult;
    }
}
